java怎么下载文件

2024-09-28 14:20:20 14 Admin
网站维护

 

在Java中,可以使用多种方法来下载文件,其中最常用的方式是通过URLConnection或HttpClient类来实现。以下是两种方法的详细介绍:

 

1. 使用URLConnection类下载文件:

 

```java

import java.io.*;

import java.net.*;

 

public class FileDownloader {

public static void downloadFile(String fileUrl

String savePath) {

try {

URL url = new URL(fileUrl);

HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

int responseCode = httpConn.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

InputStream inputStream = httpConn.getInputStream();

FileOutputStream outputStream = new FileOutputStream(savePath);

int bytesRead = -1;

byte[] buffer = new byte[1024];

while ((bytesRead = inputStream.read(buffer)) != -1) {

outputStream.write(buffer

0

bytesRead);

}

outputStream.close();

inputStream.close();

System.out.println("File downloaded successfully.");

} else {

System.out.println("Server returned HTTP response code: " + responseCode);

}

httpConn.disconnect();

} catch (IOException e) {

e.printStackTrace();

}

}

 

public static void main(String[] args) {

String fileUrl = "http://example.com/file.txt";

String savePath = "C:/Downloads/file.txt";

downloadFile(fileUrl

savePath);

}

}

```

 

2. 使用HttpClient类下载文件:

 

```java

import java.io.*;

import org.apache.http.*;

import org.apache.http.client.methods.*;

import org.apache.http.impl.client.*;

 

public class FileDownloader {

public static void downloadFile(String fileUrl

String savePath) {

try {

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpGet httpGet = new HttpGet(fileUrl);

CloseableHttpResponse response = httpClient.execute(httpGet);

HttpEntity entity = response.getEntity();

if (entity != null) {

InputStream inputStream = entity.getContent();

FileOutputStream outputStream = new FileOutputStream(savePath);

int bytesRead = -1;

byte[] buffer = new byte[1024];

while ((bytesRead = inputStream.read(buffer)) != -1) {

outputStream.write(buffer

0

bytesRead);

}

outputStream.close();

inputStream.close();

System.out.println("File downloaded successfully.");

}

 

httpClient.close();

} catch (IOException e) {

e.printStackTrace();

}

}

 

public static void main(String[] args) {

String fileUrl = "http://example.com/file.txt";

String savePath = "C:/Downloads/file.txt";

downloadFile(fileUrl

savePath);

}

}

```

 

以上是两种常用的方法来下载文件,在实际开发中可以根据具体的需求选择适合的方法来实现文件下载功能。需要注意的是,在下载文件之前需要确保文件保存路径的可写权限,并且在下载完成后及时关闭相关的流和连接,以避免资源泄露和内存泄漏问题。

Copyright © 悉地网 2018-2024.All right reserved.Powered by XIDICMS 备案号:苏ICP备18070416号-1